#!/usr/bin/env ruby

require 'rubygems'
require 'snmp'
require 'RRD'

log = File.open("log/snmp.log", "a")
host = ARGV[0]
oid = "1.3.6.1.4.1.12619.1.1.1.1"
delay = ARGV[1].to_i

#Process.daemon

$0="#{host}_torrents"

def snmp_bulkwalk(host,oid)
  port = '161'
  entries = []
  %x(snmpbulkwalk -c public -v2c #{host}:#{port} #{oid}).split("\n").each do |entry|
    parts = entry.split
    entries << {oid: parts[0], value: parts[3]}
  end
  entries

end



def define_name(oid)
  if oid =~ /.*\.1\.\d*$/
    "Hash"
  elsif oid =~ /.*\.2\.\d*$/
    "Status"
  elsif oid =~ /.*\.3\.\d*$/
    "Name"
  elsif oid =~ /.*\.4\.\d*$/
    "Size"
  elsif oid =~ /.*\.5\.\d*$/
    "Percent"
  elsif oid =~ /.*\.6\.\d*$/
    "Total_Downloaded"
  elsif oid =~ /.*\.7\.\d*$/
    "Total_Uploaded"
  elsif oid =~ /.*\.8\.\d*$/
    "Upload_speed"
  elsif oid =~ /.*\.9\.\d*$/
    "Download_speed"
  elsif oid =~ /.*\.10\.\d$*/
    "ETA"
  elsif oid =~ /.*\.11\.\d$*/
    "Peers"
  elsif oid =~ /.*\.12\.\d$*/
    "Seeds"
  end
end

def parse_data(snmp_data)
  data = {}
  snmp_data.each do |entry|
      entry[:name] = define_name(entry[:oid])

      entry[:oid] =~ /.*\.(\d*)$/
      data[$1] ||= []
      data[$1] << entry
  end
  data
end



def rrd_save(host,torrent_hash,entry)
  rrd = "rrd_data/#{host}_#{torrent_hash}_#{entry[:name]}.rrd"
  now = Time.now.to_i
  unless File.exists?(rrd)
    puts "Creating RRD"
    RRD.create(rrd, "--start", "#{now-1}", "--step", "10", "DS:a:GAUGE:600:U:U", "RRA:AVERAGE:0.5:1:300")
  end

  puts "Updating RRD"
  RRD.update(rrd, "#{now}:#{entry[:value]}")
end

loop do
  snmp_data = snmp_bulkwalk(host,oid)
  data = parse_data(snmp_data)
  data.each_value do |torrent|
    torrent.each do |entry|
      unless %W(Name Hash Status ETA Size).include? entry[:name]
        rrd_save(host, torrent[2][:value], entry)
      else
        File.open("rrd_data/#{host}_#{torrent[2][:value]}_#{entry[:name]}.txt", "w") do |fh|
          fh.write(entry[:value])
        end
      end
    end
  end
  sleep(delay)
end

